#include "EngineHeader.h"

namespace LSH
{

//------------------------------------------------------------------------
IndexBuffer::IndexBuffer(void)
{
}

//------------------------------------------------------------------------
IndexBuffer::~IndexBuffer(void)
{
}

//------------------------------------------------------------------------
void IndexBuffer::create(UINT size)
{
    bool ret = SUCCEEDED(Rander::GetSingleton().getD3DDevice()->CreateIndexBuffer(size * sizeof(DWORD), 
                            0, 
                            D3DFMT_INDEX32, 
                            D3DPOOL_DEFAULT, 
                            &_pD3dIB, 
                            NULL));
    assert(ret);
    _size = size;
}

//------------------------------------------------------------------------
void* IndexBuffer::lock(UINT size)
{
    void* pIndexs = NULL;
    bool ret = false;
    if(size == 0 || size > _size)
    {
        ret = SUCCEEDED(_pD3dIB->Lock(0, _size, (void**)&pIndexs, 0));
        assert(ret);
    }
    else
    {
        ret = SUCCEEDED(_pD3dIB->Lock(0, size, (void**)&pIndexs, 0));
        assert(ret);
    }
    return pIndexs;
}

//------------------------------------------------------------------------
void IndexBuffer::unlock()
{
    _pD3dIB->Unlock();
}

//------------------------------------------------------------------------
void IndexBuffer::map(void* pIndexs, UINT size)
{
    void* pMemory = lock();
    memcpy(pMemory, pIndexs, size);
    unlock();
}

//------------------------------------------------------------------------
void IndexBuffer::SetAsIndicesSource()
{
    IDirect3DDevice9* pDevice = Rander::GetSingleton().getD3DDevice();
    pDevice->SetIndices(_pD3dIB);
}

} // LSH
